package com.tedu.startbooksstore.service.impl;

import com.tedu.startbooksstore.ex.ServiceException;
import com.tedu.startbooksstore.mapper.CategoryMapper;
import com.tedu.startbooksstore.pojo.dto.CategoryAddNewDTO;
import com.tedu.startbooksstore.pojo.entity.Category;
import com.tedu.startbooksstore.pojo.vo.CategoryListItemVO;
import com.tedu.startbooksstore.service.ICategoryService;
import com.tedu.startbooksstore.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Service
@Slf4j
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public void insert(CategoryAddNewDTO categoryAddNewDTO) {
        log.debug("开始处理添加分类业务");
        //获得分类的名称
        String categoryName = categoryAddNewDTO.getCategoryName();
        int rows = categoryMapper.countByCategoryName(categoryName);
        //判断分类是否已经存在
        if (rows!=0){
            String message="该分类已存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        //判断分类名称是否在2-10字之间
        if (categoryName.length()<2 || categoryName.length()>10){
            String message="分类名称不在2-10字之间";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Category category=new Category();
        BeanUtils.copyProperties(categoryAddNewDTO,category);
        category.setGmtCreate(LocalDateTime.now());
        category.setGmtModified(LocalDateTime.now());
        log.debug("准备添加分类:{}",category);
        categoryMapper.insert(category);
        log.debug("添加成功");

    }

    @Override
    public List<CategoryListItemVO> list() {
        log.debug("开始处理分类列表的业务");
        return categoryMapper.list();
    }
}
